"""
@File: user.py
@Project: 约个球
@Author: zhangjian
@Time: 2022.8.27 15:36
@Description: None
"""
from werkzeug.security import check_password_hash
from wtforms import Form, StringField
from wtforms.validators import DataRequired, Email, Regexp, ValidationError, email
from model.user import UserManager


class UserForm(Form):
    """对客户端传递过来的参数进行校验
    变量名需要和客户端传递的字段名一致"""
    username = StringField(validators=[DataRequired()])
    email = StringField(validators=[DataRequired(), Email(message="邮箱不合法")])
    password = StringField(validators=[DataRequired(), Regexp(r'\w{6,18}', message="密码不符合要求")])
    # phone = StringField(validators=[DataRequired(), Regexp(r'1\d{10}', message="电话不符合要求+")])

    def validate_email(self, value):
        """自定义验证器，验证邮箱是否唯一
        自定义检查字段 方法名：validate_你要检查的字段
        value 客户端传递过来的email字段值"""
        if UserManager.query.filter_by(email=value.data).first():
            from libs.error_code import EmailAlreadyExistException
            raise EmailAlreadyExistException

    def validate_username(self, value):
        """对数据进行修改，给客户端传进来的所有用户名都加一个sanchuang-开头"""
        value.data = "sanchuang-" + value.data


class LoginForm(Form):
    """用户登录验证"""
    username = StringField(validators=[DataRequired()])
    password = StringField(validators=[DataRequired()])

    def validate(self):
        """重写了validate方法"""
        user = UserManager.query.filter_by(email=self.username.data).first()
        # 如果用户存在，并且密码验证通过
        if user and check_password_hash(user.password, self.password.data):
            return user
        elif not user:
            from libs.error_code import EmailValidateException
            raise EmailValidateException
        else:
            from libs.error_code import PasswordValidateException
            raise PasswordValidateException
